package com.voxel.sense.infomsg.module.task.operation;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.interfaces.listener.onClickSubmitListener;
import com.voxel.sense.infomsg.interfaces.listener.onMyItemClickListener;
import com.voxel.sense.infomsg.module.task.TaskListAdapter;
import com.voxel.sense.infomsg.module.task.execution.TaskExecutionActivity;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.dropmenu.DropDownMenu;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.adapter.FilterRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.MyTaskListInfoEntity;

/**
 * 单个任务状态的任务列表
 * Created by ChenYiYao on 2017/11/20.
 */

public class TaskOperationActivity extends BViewActivity<TaskOperateContract.Presenter> implements
        TaskOperateContract.View {

    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.drop_down_menu)
    DropDownMenu drop_down_menu;

    private EmptyView empty_view;//占位的空界面布局
    private SmartRefreshLayout refresh_layout;//下拉刷新头
    private RecyclerView recycle_view;//任务列表
    private RecyclerView area_recycler;//地区筛选列表
    private RecyclerView type_recycler;//行业筛选列表
    private RecyclerView mSmart_recycler;//只能筛选筛选列表

    private TaskListAdapter mAdapter;//任务列表适配器
    private FilterRecyclerAdapter mAreaListAdapter;  //地区适配器
    private FilterRecyclerAdapter mTaskTypeAdapter; //行业类型适配器
    private FilterRecyclerAdapter mSmartAdapter; //行业类型适配器

    //TODO:隐藏区域筛选条件
//    private String headers[] = {"区域", "任务类型", "智能筛选"};
    private String headers[] = {"任务类型", "智能筛选"};
    private String mCurrentCity = Constants.DEFAULT_CITY;

    private boolean isFirstEnter = true;//是否首次进入
    private String mType;

    /**
     * @param type 类型 0：未接收 1:执行中 2：执行完成  不传或-1:查询个人所有相关任务
     * @param city 查询的城市
     */
    public static void show(Context context, int type, String city) {
        Intent intent = new Intent(context, TaskOperationActivity.class);
        intent.putExtra(IntentConstants.STYPE, type);
        intent.putExtra(IntentConstants.LOCATION_CITY, city);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected TaskOperateContract.Presenter initPresenter() {
        return new TaskOperatePresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_task_operate;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            int type = bundle.getInt(IntentConstants.STYPE, -1);
            String city = bundle.getString(IntentConstants.LOCATION_CITY);
//            this.mType = type;

            if (!TextUtils.isEmpty(city)) {
                this.mCurrentCity = city;
            }
        }
        return super.initArgs(bundle);
    }

    @Override
    protected void initData() {
        super.initData();
        titlebar.setTitleText("任务管理");
//        mPresenter.setTaskType(mType);
        if (mType == Constants.TASK_ACTION_TYPE) {
            titlebar.setTitleText(getResources().getString(R.string.action_task));
        } else if (mType == Constants.TASK_FINISH_TYPE) {
            titlebar.setTitleText(getResources().getString(R.string.audit_task));
        } else if (mType == Constants.TASK_UNACCEPT_TYPE) {
            titlebar.setTitleText(getResources().getString(R.string.accept_task));
        }
        initMenu();
        if (isFirstEnter) {
            refresh_layout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
        //初始化任务列表
//        mAdapter = new TaskListAdapter(mType);
        onChangeTaskListener();
        recycle_view.setLayoutManager(new LinearLayoutManager(this));
        recycle_view.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        recycle_view.setAdapter(mAdapter);

    }

    @Override
    protected void initEven() {
        super.initEven();

        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                handleRefresh();
            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                handleLoad();
            }
        });

        empty_view.addRefreshBtnEvent(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                empty_view.triggerOk();
                boolean b = refresh_layout.autoRefresh();
                //刷新过于频繁会导致失败，不会回调刷新方法
                if (!b) {
                    showEmptyView("",true);
                }
            }
        });

    }

    private void handleRefresh() {
        if (NetworkUtils.isConnected()) {
            //重新刷新，需要改变状态，可以加载更多数据
            refreshData();
        } else {
            refresh_layout.finishRefresh();
            showEmptyView(getString(R.string.network_unavailable),true);
        }
    }

    private void handleLoad() {
        if (NetworkUtils.isConnected()) {
            mPresenter.doLoadMoreData();
        } else {
            showEmptyView(getString(R.string.network_unavailable),true);
            refresh_layout.finishLoadMore();
        }
    }

    private void refreshData() {
        refresh_layout.setNoMoreData(false);
        mPresenter.doLoadData();
    }


    private void initMenu() {
        createAreaList();//创建地区筛选列表 served
        createTaskTypeList();//创建行业类型筛选列表
        createSmartList();//创建智能筛选列表

        //将列表添加到菜单中
        List<View> popupViews = new ArrayList<>();//筛选栏目的集合simplified
//        popupViews.add(area_recycler);
        popupViews.add(type_recycler);
        popupViews.add(mSmart_recycler);

        View view = LayoutInflater.from(this).inflate(R.layout.layout_recycler_emptty, null);
        refresh_layout = view.findViewById(R.id.refresh_layout);
        recycle_view = view.findViewById(R.id.recycle_view);
        empty_view = view.findViewById(R.id.empty_view);
        empty_view.bind(refresh_layout);

        //将主题列表添加入上级控件中
        drop_down_menu.setDropDownMenu(Arrays.asList(headers), popupViews, view);
    }

    /**
     * 改变任务状态
     */
    private void onChangeTaskListener() {
        mAdapter.setOnchangStatuBtn(new onMyItemClickListener() {
            @Override
            public void onItemClick(int posision) {
//                mPresenter.doOperateTask(mType, posision);
            }
        });
    }

    private void createAreaList() {
        //地址选中列表
        area_recycler = new RecyclerView(this);
        mAreaListAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.TYPE_AREA);
        setMenuAdapterConfig(area_recycler, mAreaListAdapter, "地区选中");
        mPresenter.doLoadRegionMenuData(mCurrentCity);
    }


    /**
     * 创建任务类型列表
     */
    private void createTaskTypeList() {
        //地址选中列表
        type_recycler = new RecyclerView(this);
        mTaskTypeAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.TYPE_IDUSTRY);
        setMenuAdapterConfig(type_recycler, mTaskTypeAdapter, "全类型");
        //加载数据
        mPresenter.doLoadTaskTypeMenuData();
    }

    /**
     * 创建智能筛选类型列表  配置
     */
    private void createSmartList() {
        //地址选中列表
        mSmart_recycler = new RecyclerView(this);
        //创建适配器
        mSmartAdapter = new FilterRecyclerAdapter(MenuListItemListener, Constants.Type_Smart);
        setMenuAdapterConfig(mSmart_recycler, mSmartAdapter, "全类型");
        mSmartAdapter.setSingleSelect(true);
        //加载数据
        mPresenter.doLoadOtherMenuData();
    }

    private void setMenuAdapterConfig(RecyclerView rv, FilterRecyclerAdapter adapter, String headText) {
        //设置下划线
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider));
        adapter.setHeadText(headText);
        rv.setAdapter(adapter);
        //设置提交监听
        adapter.setSubmitListener(new onClickSubmitListener() {
            @Override
            public void onSubmit(List list, String type) {
                SubmitSearch();
            }
        });
    }

    //提交筛选条件，进行刷新数据
    private void SubmitSearch() {
        drop_down_menu.closeMenu();
        mPresenter.doSubmitSearchCondition();
        refresh_layout.autoRefresh();
    }

    /**
     * 菜单列表item点击监听
     */
    RecyclerAdapter.AdapterListenerImpl MenuListItemListener = new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
        @Override
        public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
            super.onItemClick(holder, bean);
//            if (bean == null)
//                return;
            mPresenter.changeSearchCondition(bean);
        }
    };


    @Subscribe
    public void onEvnetBus(EventEntity event) {
        if (event == null) {
            return;
        }
        if (mType == Constants.TASK_FINISH_TYPE) {
            //判断当前界面是否是审核界面，以免网络过慢时跳转到其它界面，操作到错误的类型
            if (EventBusConstants.CHECK_TASK_PASS.equals(event.key) || EventBusConstants.CHECK_TASK_NO_PASS.equals(event.key)) {
                //接到审核完成通知
                reniveSpcItem(event);
            }
        } else if (mType == Constants.TASK_ACTION_TYPE) {
            if (EventBusConstants.TASK_ACTION_FINISH.equals(event.key)) {
                //任务执行完成通知
                reniveSpcItem(event);
            }
        }
    }

    private void reniveSpcItem(EventEntity event) {
        String num = (String) event.value;
        List<MyTaskListInfoEntity.BodyBean.TaskInfoListBean> items = mAdapter.getItems();
        for (int i = items.size() - 1; i >= 0; i--) {
            MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean = items.get(i);
            if (bean.getTaskNumber().equals(num)) {
                items.remove(i);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public RecyclerAdapter<MyTaskListInfoEntity.BodyBean.TaskInfoListBean> getRecyclerViewAdapter() {
        return mAdapter;
    }

    @Override
    public void onAdapterDataChanged() {
        empty_view.triggerOkOrEmpty(mAdapter.getItemCount() > 0);
    }

    @Override
    public void showEmptyView(String desc, boolean btnVisible) {
        boolean b = mAdapter.getItemCount() > 0;
        if (!b && !TextUtils.isEmpty(desc)) {
            empty_view.triggerError(desc);
        } else if (b) {
            //发生错误，列表有数据，不能显示空界面
            super.showError(desc);
        } else if (!NetworkUtils.isConnected()) {
            empty_view.triggerNetError();
        } else {
            empty_view.triggerEmpty();
        }
    }

    @Override
    public void onNotifyRegionData(List<ConditionBean> datas) {
        mAreaListAdapter.replace(datas);
    }

    @Override
    public void onNotifyTaskTypeData(List<ConditionBean> datas) {
        mTaskTypeAdapter.replace(datas);
    }

    @Override
    public void onNotifyOtherData(List<ConditionBean> datas) {
        mSmartAdapter.replace(datas);
    }

    @Override
    public void onShowNoMore(boolean b) {
        refresh_layout.setNoMoreData(b);
    }

    @Override
    public void onRefreshFinish() {
        if (isFirstEnter) {
            isFirstEnter = false;
        }
        refresh_layout.finishRefresh();
        empty_view.triggerOkOrEmpty(mAdapter.getItemCount() > 0);
    }

    @Override
    public void onLoadMoreFinish() {
        refresh_layout.finishLoadMore();
    }

    @Override
    public void onExecuteTask(MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean) {
        if (bean.getTaskStatusId().equals(Constants.TASK_ACTION_TYPE + "")) {
            TaskExecutionActivity.show(TaskOperationActivity.this, bean);
        } else {
            //暂时不可执行
            DialogImpl.getInstance().showMessageDialog(TaskOperationActivity.this, "温馨提示",
                    "该任务的其它组员还没接收任务，暂不可执行", new DialogCallBack() {
                        @Override
                        public void onClick(int what) {

                        }
                    });
        }
    }

    @Override
    public void onCheckTask(MyTaskListInfoEntity.BodyBean.TaskInfoListBean bean) {
//        CheckTaskActivity.show(this, bean);
    }

    @Override
    public void UpTaskStatus() {
        mAdapter.notifyDataSetChanged();
    }
}
